import React, {Component} from 'react';
import {
  View,
  Text,
  ActivityIndicator,
  FlatList,
  Image,
  StyleSheet,
  TouchableHighlight,
} from 'react-native';

// 导入图标相关的组件
import Icon from 'react-native-vector-icons/FontAwesome';
// 导入路由的组件
import {Actions} from 'react-native-router-flux';

export default class MovieList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      movies: [],
      nowPage: 1,
      pageSize: 20,
      //   totalPage: 0,
      isLoading: true,
    };
  }

  UNSAFE_componentWillMount() {
    this.getMoviesByPage();
  }

  render() {
    return (
      <View style={{backgroundColor: 'white', height: '100%'}}>
        {this.renderList()}
      </View>
    );
  }

  // 根据页码获取电影列表
  getMoviesByPage = () => {
    const start = this.state.nowPage + 1;
    const url = `https://movie.douban.com/j/search_subjects?type=movie&tag=%E7%83%AD%E9%97%A8&sort=recommend&page_limit=${this.state.pageSize}&page_start=${start}`;
    fetch(url)
      .then(res => res.json())
      .then(data => {
        this.setState({
          isLoading: false,
          movies: this.state.movies.concat(data.subjects),
        });
      });
  };

  // 渲染电影列表的方法
  renderList = () => {
    if (this.state.isLoading) {
      return <ActivityIndicator size="large" color="blue"></ActivityIndicator>;
    }
    return (
      <FlatList
        data={this.state.movies}
        keyExtractor={(item, i) => i} // 解决 key 问题
        renderItem={({item}) => this.renderItem(item)} // 调用方法，去渲染每一项
        ItemSeparatorComponent={this.renderSeparator}
        onEndReachedThreshold={0.5}
        onEndReached={this.loadNextPage}
      />
    );
  };

  // 渲染每项电影
  renderItem = item => {
    return (
      <TouchableHighlight
        underlayColor="#fff"
        onPress={() => {
          Actions.moviedetail({id: item.id});
        }}>
        <View style={{flexDirection: 'row', padding: 10}}>
          <Image
            source={{uri: item.cover}}
            style={{width: 100, height: 140, marginRight: 10}}></Image>
          <View style={{justifyContent: 'center'}}>
            <Text style={{marginBottom: 10}}>
              <Text style={styles.movieTitle}>电影名称：</Text>
              {item.title}
            </Text>
            <Text>
              <Text style={styles.movieTitle}>豆瓣评分：</Text>
              {item.rate}分
            </Text>
          </View>
        </View>
      </TouchableHighlight>
    );
  };

  // 渲染分割线
  renderSeparator = () => {
    return <View style={styles.separator}></View>;
  };

  // 加载下一页
  loadNextPage = () => {
    this.setState(
      {
        nowPage: this.state.nowPage + 1,
      },
      function () {
        this.getMoviesByPage();
      },
    );
  };
}

var styles = StyleSheet.create({
  movieTitle: {
    fontWeight: 'bold',
  },

  separator: {
    borderBottomColor: '#ccc',
    borderBottomWidth: 1,
    marginLeft: 10,
    marginRight: 10,
  },
});
